using System.Collections;
using System.Collections.Generic;
using Moliser3;
using UnityEngine;
/// <summary>
/// 绘制阵法的方法
/// </summary>
public class DrawMagic : BaseManager<DrawMagic>
{
    //传入坐标 新建阵法
    //插下旗子 样条线条生成
    //再次按下旗子  生成一条线段  闭合样条线生成

    MagicLine startSpLine;//起始样条线
    MagicLine closeSpLine;//结束样条线
    List<MagicLine> stayCreatLines;  //待生成的线条
    List<Vector3> graphDotList; //图形的所有点位置
    List<Vector3> zeroDotList;//已有图形点+实时坐标点
    Vector3 mousePos;//鼠标位置
    Vector3 drawStartPos;//当前绘制的起始位置
    Vector3 drawEndPos;//当前绘制的结束位置
    Vector3 floorDotPos;// 地板位置
    GameObject magicCircles; //所有法阵对象的父对象
    GameObject modelCirclesline;
    GameObject dot;//模型阵眼
    Vector3[] stayDrawLine;
    Vector3[] closeDrawLine;
    Vector3 cloaseVec3;
    Vector3 newLineVec3;
    Vector3 stayVec;
    Vector3 dotVec3;
    E_CreatNewLine_State newLineState;
    E_LastLine_State newLastLineState;
    bool isDrawNewLine = true;
    bool isDraw;
    public Vector3 MousePos { get => mousePos; set => mousePos = value; }
    public Vector3 DrawStartPos { get => drawStartPos; set => drawStartPos = value; }
    public Vector3 DrawEndPos { get => drawEndPos; set => drawEndPos = value; }
    public GameObject MagicCircles { get => magicCircles; set => magicCircles = value; }

    //Vector3[] lineVec3 = new Vector3[2];
    List<Vector3[]> lineVec3List = new List<Vector3[]>();
    /// <summary>
    /// 初始化
    /// </summary>
    public void Init()
    {

        /*场景实例化对象*/
        MagicCircles = new GameObject("MagicCircles");
        MagicCircles.transform.position = Vector3.zero;


        dot = GameObject.Instantiate(Resources.Load<GameObject>("ObjectRes/Dot"));
        dot.transform.position = Vector3.zero;
        dot.transform.LookAt(Camera.main.gameObject.transform.position);
        dot.transform.gameObject.SetActive(false);
        dot.transform.SetParent(MagicCircles.transform);

        stayCreatLines = new List<MagicLine>();
        //stayCreatLines.Clear();
        graphDotList = new List<Vector3>();
        zeroDotList = new List<Vector3>();
        mousePos = new Vector3();
        drawStartPos = new Vector3();
        drawEndPos = new Vector3();
        floorDotPos = new Vector3(); dotVec3 = new Vector3();
        stayDrawLine = new Vector3[2];
        closeDrawLine = new Vector3[2];
        /*帧更新监听*/
        MonoMgr.GetInstance().AddUpdateListener(Drawline);//添加帧更新监听
        MonoMgr.GetInstance().AddUpdateListener(MousePosAmendment); //添加帧更新监听
        /*事件监听*/
        EventService.AddEventListener<bool>(E_Event_Type.StartDrawMagicLine, TouchDraw);
        EventService.AddEventListener<bool>(E_Event_Type.EndDrawMagicLine, CreatDraw);
        EventService.AddEventListener(E_Event_Type.RevocationMagicLine, RevocationDrawLine);
        isDraw = false;
        newLineState = E_CreatNewLine_State.Failed;
        newLastLineState = E_LastLine_State.Failed;
        startSpLine = new MagicLine(false, Vector3.zero, Vector3.zero, "startSpLine", E_MagicLine_Type.ModelLine, MagicCircles.transform);
        closeSpLine = new MagicLine(false, Vector3.zero, Vector3.zero, "closeSpLine", E_MagicLine_Type.ModelLine, MagicCircles.transform);

    }

    /// <summary>
    /// 鼠标点击绘制新位置
    /// </summary>
    public void ClickToDraw(Vector3 pointPos)
    {
        if (isDraw && isDrawNewLine)
        {
            if (graphDotList.Count < 1)
            {
                DrawStartPos = new Vector3(pointPos.x, 0.3f, pointPos.z);
                MagicLine line = new MagicLine(false, Vector3.zero, Vector3.zero, "line", E_MagicLine_Type.MagicLine, MagicCircles.transform);
                stayCreatLines.Add(line);
                graphDotList.Add(DrawStartPos);
                newLineState = E_CreatNewLine_State.Pass;
            }
            else
            {
                if (newLineState == E_CreatNewLine_State.Pass)
                {
                    DrawEndPos = new Vector3(pointPos.x, 0.3f, pointPos.z);
                    Vector3[] lineVec = { graphDotList[graphDotList.Count - 1], DrawEndPos };
                    lineVec3List.Add(lineVec);
                    graphDotList.Add(DrawEndPos);
                    MagicLine line = new MagicLine(true, DrawEndPos, DrawStartPos, "line", E_MagicLine_Type.MagicLine, MagicCircles.transform);
                    DrawStartPos = DrawEndPos;

                    stayCreatLines.Insert(stayCreatLines.Count - 1, line);
                    stayCreatLines[stayCreatLines.Count - 1].SetLine(true, graphDotList[0], DrawEndPos);
                    newLastLineState = IsLastLineOfAllow();
                }

            }
        }
    }
    /// <summary>
    /// 实时显示线条方法
    /// </summary>
    public void RealTimeDrawDot()
    {
        if (zeroDotList.Count >= 3)
        {
            if (dot.activeSelf == false)
            {
                dot.SetActive(isDraw);
            }
            dotVec3 = AreaController.GetInstance().CreatCenterDot(zeroDotList);
            dot.transform.position = dotVec3;
        }
    }
    public void Drawline()
    {
        if (isDraw)
        {
            Drawing();
        }
    }

    public void Drawing()
    {
        if (stayCreatLines.Count > 1)
        {
            startSpLine.SetLine(true, DrawStartPos, floorDotPos);
            closeSpLine.SetLine(true, floorDotPos, graphDotList[0]);
        }
        else
        {
            startSpLine.SetLine(false, Vector3.zero, Vector3.zero);
            closeSpLine.SetLine(false, Vector3.zero, Vector3.zero);
        }
    }

    public void TouchDraw(bool draw)
    {
        isDraw = draw;
    }

    public void CreatDraw(bool draw)
    {
        if (newLastLineState == E_LastLine_State.Pass)
        {
            isDraw = draw;
            //MagicLine closeLine = new MagicLine(true, DrawStartPos, graphDotList[0], "line", E_MagicLine_Type.ModelLine, MagicCircles.transform);
            //stayCreatLines.Add(closeLine);
            startSpLine.SetLine(false, Vector3.zero, Vector3.zero);
            closeSpLine.SetLine(false, Vector3.zero, Vector3.zero);
            dot.SetActive(false);
            //创建法阵
            MagicGraph magicGraph = new MagicGraph(stayCreatLines, graphDotList, "Test");
            MagicController.GetInstance().AddNewMagicGraph(magicGraph);
            //清场
            stayCreatLines.Clear();
            graphDotList.Clear();
            MousePos = Vector3.zero;
            DrawEndPos = Vector3.zero;
            DrawStartPos = Vector3.zero;

            stayDrawLine = new Vector3[2];
            closeDrawLine = new Vector3[2];
            lineVec3List.Clear();

        }


    }
    /// <summary>
    /// 鼠标实时位置设置，与上一次位置不同就更新
    /// </summary>
    public void MousePosAmendment()
    {
        if (isDraw)
        {
            if ((floorDotPos.x != MousePos.x) || (floorDotPos.z != MousePos.z))
            {
                isDrawNewLine = true;
                floorDotPos = new Vector3(MousePos.x, 0.3f, MousePos.z);
                zeroDotList.Clear();
                zeroDotList.AddRange(graphDotList);
                zeroDotList.Add(floorDotPos);
                if (graphDotList.Count > 0)
                {
                    stayDrawLine[0] = graphDotList[graphDotList.Count - 1];
                }
                stayDrawLine[1] = floorDotPos;
                closeDrawLine[0] = floorDotPos;
                closeDrawLine[1] = zeroDotList[0];
                RealTimeDrawDot();
                newLineState = IsAllowDrawNewLine();
                if (newLineState == E_CreatNewLine_State.Failed)
                {
                    EventService.EventTrigger<E_MagicModeLine_State>(E_Event_Type.ModelLineState, E_MagicModeLine_State.WrongLine);
                }
                else
                {
                    EventService.EventTrigger<E_MagicModeLine_State>(E_Event_Type.ModelLineState, E_MagicModeLine_State.CorrectLine);
                }
            }
        }
    }

    /// <summary>
    /// 新画的线是否相交
    /// </summary>
    /// <returns></returns>
    E_CreatNewLine_State IsAllowDrawNewLine()
    {
        cloaseVec3 = closeDrawLine[0] - closeDrawLine[1];
        stayVec = stayDrawLine[1] - stayDrawLine[0];
        if (lineVec3List.Count > 0)
        {
            newLineVec3 = lineVec3List[lineVec3List.Count - 1][0] - lineVec3List[lineVec3List.Count - 1][1];
        }
        if (newLineVec3.normalized == stayVec.normalized)
        {
            Debug.Log("非法线条交叉");
            //事件触发 事件不合法
            return E_CreatNewLine_State.Failed;
        }
        for (int i = 0; i < lineVec3List.Count - 1; i++)
        {
            if (Moliser3Tool.IsLinesIntersectInPlaneXZ(stayDrawLine, lineVec3List[i]))
            {
                Debug.Log("非法线条交叉");
                //事件触发 事件不合法
                return E_CreatNewLine_State.Failed;
            }
        }
        return E_CreatNewLine_State.Pass;
    }
    Vector3 lastLineVec;
    Vector3[] lastLineVecGr = new Vector3[2];
    E_LastLine_State IsLastLineOfAllow()
    {
        if (lineVec3List.Count > 0)
        {
            lastLineVec = graphDotList[0] - graphDotList[graphDotList.Count - 1];
            lastLineVecGr[0] = graphDotList[graphDotList.Count - 1];
            lastLineVecGr[1] = graphDotList[0];
        }
        if (lastLineVec.normalized == (lineVec3List[0][1] - lineVec3List[0][0]).normalized)
        {
            Debug.Log("闭口线非法线条交叉1");
            //事件触发 事件不合法
            return E_LastLine_State.Failed;
        }
        for (int i = 1; i < lineVec3List.Count - 1; i++)
        {
            if (Moliser3Tool.IsLinesIntersectInPlaneXZ(lastLineVecGr, lineVec3List[i]))
            {
                Debug.Log("闭口线非法线条交叉2");
                //事件触发 事件不合法
                return E_LastLine_State.Failed;
            }
        }
        return E_LastLine_State.Pass;
    }
    /// <summary>
    /// 撤销操作
    /// </summary>
    public void RevocationDrawLine()
    {
        if (isDraw)
        {
            if (stayCreatLines.Count >= 2)
            {
                stayCreatLines[stayCreatLines.Count - 2].Recycle();
                stayCreatLines.RemoveAt(stayCreatLines.Count - 2);
                lineVec3List.RemoveAt(lineVec3List.Count - 1);
                graphDotList.RemoveAt(graphDotList.Count - 1);
                stayCreatLines[stayCreatLines.Count - 1].SetLine(true, graphDotList[graphDotList.Count - 1], graphDotList[0]);
                zeroDotList.Clear();
                zeroDotList.AddRange(graphDotList);
                zeroDotList.Add(floorDotPos);
                DrawStartPos = graphDotList[graphDotList.Count - 1];
                startSpLine.SetLine(true, DrawStartPos, floorDotPos);
                closeSpLine.SetLine(true, floorDotPos, graphDotList[0]);
            }
            else
            {
                if (stayCreatLines.Count > 0)
                {
                    stayCreatLines[0].Recycle();
                }
                stayCreatLines.Clear();
                graphDotList.Clear();
                MousePos = Vector3.zero;
                DrawEndPos = Vector3.zero;
                DrawStartPos = Vector3.zero;
                startSpLine.SetLine(false, Vector3.zero, Vector3.zero);
                closeSpLine.SetLine(false, Vector3.zero, Vector3.zero);
                dot.SetActive(false);
            }
        }
    }
}
/// <summary>
/// 当前图形的状态 Pass 合格，Failed 不合格
/// </summary>
enum E_CreatNewLine_State
{
    Pass,
    Failed
}

enum E_LastLine_State
{
    Pass,
    Failed
}
